﻿using MediatR;
using T.ApprovalRecord;
using T.Materials.API.Application.Command.MaterialRequisitionCommand;
using T.Materials.API.Application.Command.MaterialStoreCommand;
using T.Materials.Repository.MaterialsImpl;
using T.Materials.Repository.MaterialsInterface;
using static T.Materials.Domain.Enum.Enums;

namespace T.Materials.API.Application.CommandHandler.MaterialRequisitionCommandHandler
{
    /// <summary>
    /// 更新物资领用状态命令处理器
    /// </summary>
    public class UpdadteMaterialRequisitionStatusCommandHandler : IRequestHandler<UpdadteMaterialRequisitionStatusCommand, int>
    {
        /// <summary>
        /// 物资领用仓储接口
        /// </summary>
        protected readonly IMaterialRequisitionRepository materialRequisitionRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="materialRequisitionRepository">物资领用仓储接口</param>
        public UpdadteMaterialRequisitionStatusCommandHandler(IMaterialRequisitionRepository materialRequisitionRepository)
        {
            this.materialRequisitionRepository = materialRequisitionRepository;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException"></exception>
        public async Task<int> Handle(UpdadteMaterialRequisitionStatusCommand request, CancellationToken cancellationToken)
        {
            var res = await materialRequisitionRepository.GetModelAsync(request.MaterialRequisitionId);

            ApprovalRecordd approvalRecord;
            if (res.ApprovalStatus == ApprovalStatus.待提交)
            {
                res.ApprovalStatus = ApprovalStatus.待审批;
            }
            else if (res.ApprovalStatus == ApprovalStatus.已拒绝)
            {
                res.ApprovalStatus = ApprovalStatus.待审批;
            }
            else
            {
                // 处理其他状态（如果需要）
                throw new InvalidOperationException("未知的审批状态");
            }
            return await materialRequisitionRepository.UpdateAsync(res);
        }
    }
}
